var express = require("express");
const axios = require("axios");
var router = express.Router();
const qs = require("qs");
/* GET home page. */
router.get("/zyw", function (req, res, next) {
  res.render("index", {
    title: "Express"
  });
});
router.post("/ping", function (req, res, next) {
  res.send("UFace post ok");
});



/*face++ 的授权*/
let FAPI_KEY = "Qae_jfvfjN6rSw9bGt2VTR_B9Gg7pF2W";
let FSECRET_KEY = "riS8QYuqbI6pR-sX9fjs13nPZX96wUA6";

let multiparty = require("multiparty");
let fs = require("fs");
var sex = 0
router.get("/test", function (req, res, next) {
  sex = req.query["sex"]
  res.send(sex);
})
router.post("/file/merge/uploading", function (req, res, next) {
  var form = new multiparty.Form({
    /* 上传的文件存放 */
    uploadDir: "./public/files/"
  });
  /* multiparty解析form文件*/
  form.parse(req, function (err, fields, files) {
    var filesTmp = JSON.stringify(files, null, 2);

    if (err) {
      console.log("解析错误" + err);
    } else {
      var inputFile = files.file[0];
      var uploadedPath = inputFile.path;
      /* 上传的文件 */
      var imageFace = fs.readFileSync(uploadedPath);

      // var base64ImgFace = Buffer.from(imageFace).toString("base64");
      var base64ImgFace = fields.base_filepath[0]
      /* 读取模板图，编码成base64，模板要求base64 */
      //TODO:以后自己前端上传模板图

      var imageTpl = ''
      var randomindex = String(Math.floor(Math.random() * 13) + 1)
      if (sex == 1) {
        imageTpl = fs.readFileSync("./public/images/face/huge" + randomindex + ".png");
      } else {
        imageTpl = fs.readFileSync("./public/images/face/example" + randomindex + ".png");
      }

      var base64ImgTpl = Buffer.from(imageTpl).toString("base64");
      //console.log(base64ImgFace)
      // 调用函数，对图片进行压缩

      /* 请求face++接口 */
      axios({
          method: "post",
          url: "https://api-cn.faceplusplus.com/imagepp/v1/mergeface",
          data: qs.stringify({
            api_key: FAPI_KEY,
            api_secret: FSECRET_KEY,
            template_base64: base64ImgTpl,
            merge_base64: base64ImgFace,
            merge_rate: 100
          })
        })
        .then(data => {
          //console.log(data);
          let senddata = {
            result: data.data.result,
            randomindex: randomindex
          }
          res.send(senddata);
        })
        .catch(e => {
          var error = e.response.data.error_message
          if (error.indexOf("NO_FACE_FOUND") != -1) {
            res.status(400).send("error")
          } else if (error.indexOf("CONCURRENCY_LIMIT_EXCEEDED") != -1) {
            res.status(500).send("error")
          }
        });
    }
  });
});


https: module.exports = router;